<?php

namespace app\api\controller\v1;
use app\api\service\CmsToken;
use app\api\service\Token;
use app\api\service\UserToken;
use app\api\validate\CmsUserValidate;
use app\api\validate\TokenGet;
use app\lib\exception\ParamException;
use think\Db;
use think\facade\Request;

class User
{
    public function getToken($code=""){
        //验证参数
        // $code='061U2DeH1VExG80YQJaH1KjgeH1U2De9';
        $code=request()->post('code');
        (new TokenGet())->goCheck(['code'=>$code]);
        $user=new UserToken($code);
        $token=$user->getToken();
        return ['token'=>$token];
    }

    /**
     * token 验证接口
     * @param string $token
     */
    public function verifyToken($token=""){
        if(!$token){
            throw  new ParamException(['msg'=>'token不能为空']);
        }
        $res=Token::tokenVerify($token);
        return ['valid'=>$res];
    }

    /**
     * cms获取token的接口方法
     */
    public function cmsToken(){
        $params=Request::post();
        $res=(new CmsUserValidate())->goCheck($params);
        if($res){
            $userName=$params['ac'];
            $pwd=$params['se'];
            $data=Db::table("third_app")->where("app_id",$userName)->find();
            if(!$data){
                throw new ParamException(['msg'=>"用户不存在"]);
            }
            if($data["app_secret"]!=$pwd){
                throw new ParamException(['msg'=>"密码错误"]);
            }
            //如果用户名密码验证通过,返回token
            $token=(new cmsToken)->getCmsToken($data);
            return ["token"=>$token];
        }

    }

}
